let timeout = null;
export default {
    /**
     * 格式化字节数为适当的单位 (KB, MB, GB)
     * @param {number} bytes - 字节数
     * @returns {string} 格式化后的字符串
     */
    formatBytes(bytes = 0) {
        if (bytes === 0) return '0 B';
        const k = 1024;
        const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    },
    /**
     * 计算下载进度和格式化文件大小
     * @param {number} completedLength - 已下载的字节数
     * @param {number} totalLength - 文件总字节数
     * @returns {object} 包含已下载大小、总大小和进度百分比的对象
     */
    /**
     * 格式化时间为适当的单位 (秒, 分, 小时)
     * @param {number} seconds - 秒数
     * @returns {string} 格式化后的字符串
     */
    formatTime(seconds) {
        if (seconds === 0) return '0 s';
        const units = [
            {label: '天', seconds: 86400},
            {label: '时', seconds: 3600},
            {label: '分', seconds: 60},
            {label: '秒', seconds: 1}
        ];
        const timeParts = units.map(unit => {
            const value = Math.floor(seconds / unit.seconds);
            seconds %= unit.seconds;
            return value > 0 ? `${value}${unit.label}` : null;
        }).filter(part => part !== null);
        return timeParts.join(' ');
    },
    calculateDownloadProgress(completedLength = 0, totalLength = 0, downloadSpeed = 0) {
        const downloadedSize = this.formatBytes(completedLength);
        const totalSize = this.formatBytes(totalLength);
        const progressNum = (completedLength / totalLength * 100).toFixed(2)
        const remainingLength = totalLength - completedLength;
        const remainingTime = this.formatTime(remainingLength / downloadSpeed);
        return {
            downloadedSize,
            totalSize,
            progress: progressNum + '%',
            progressNum: +progressNum,
            remainingTime
        };
    },
    formatDownloadSpeed(downloadSpeed = 0) {
        const MB = 1048576; // 1 MB = 1048576 bytes
        const KB = 1024; // 1 KB = 1024 bytes

        if (downloadSpeed >= MB) {
            return (downloadSpeed / MB).toFixed(2) + ' MB/s';
        } else if (downloadSpeed >= KB) {
            return (downloadSpeed / KB).toFixed(2) + ' KB/s';
        } else {
            return downloadSpeed + ' B/s';
        }
    },
    getCurrentDateTime() {
        const now = new Date();
        const year = now.getFullYear(); // 获取年份
        const month = now.getMonth() + 1; // 获取月份，注意月份从0开始计数，需要加1
        const date = now.getDate(); // 获取日期
        const hour = now.getHours(); // 获取小时
        const minute = now.getMinutes(); // 获取分钟
        const second = now.getSeconds(); // 获取秒钟

        return `${year}-${month}-${date} ${hour}:${minute}:${second}`;
    },
    /**
     * 防抖原理：一定时间内，只有最后一次操作，再过wait毫秒后才执行函数
     *
     * @param {Function} func 要执行的回调函数
     * @param {Number} wait 延时的时间
     * @param {Boolean} immediate 是否立即执行
     * @return null
     */
    debounce(func, wait = 500, immediate = false) {
        // 清除定时器
        if (timeout !== null) clearTimeout(timeout);
        // 立即执行，此类情况一般用不到
        if (immediate) {
            var callNow = !timeout;
            timeout = setTimeout(function () {
                timeout = null;
            }, wait);
            if (callNow) typeof func === "function" && func();
        } else {
            // 设置定时器，当最后一次操作后，timeout不会再被清除，所以在延时wait毫秒后执行func回调方法
            timeout = setTimeout(function () {
                typeof func === "function" && func();
            }, wait);
        }
    },
    //判断是否有新版
    isNewVersion(currentVersion, newVersion) {
        const currentParts = currentVersion.split('.').map(Number);
        const newParts = newVersion.split('.').map(Number);

        for (let i = 0; i < Math.max(currentParts.length, newParts.length); i++) {
            const current = currentParts[i] || 0;
            const newVer = newParts[i] || 0;

            if (newVer > current) {
                return true;  // newVersion is newer
            } else if (newVer < current) {
                return false; // newVersion is not newer
            }
        }

        return false; // versions are equal
    }
}